package com.boruan.qq.zxgylibrary.ui.activities;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;

import butterknife.BindView;

/**
 * Created by 崔琦 on 2019/8/22.
 * des: 售后
 */

public class AfterSalesActivity extends BaseActivity {
    @BindView(R2.id.fl_add_web)
    FrameLayout flAddWeb;
	@BindView(R2.id.after_sales_webView)
    WebView afterSalesWebView;

    private CustomDialog customDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.drug_activity_after_sales;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        customDialog = new CustomDialog(this,R.style.CustomDialog);
        customDialog.show();
        //initCommonWeb(ConstantInfo.baseUrl + "refund?type=android&token=" + ConstantInfo.h5UserToken);
        initWeb(ConstantInfo.baseUrl + "refund?type=android&token=" + ConstantInfo.h5UserToken);
    }

    /**
     * 初始化web
     */
    @SuppressLint("JavascriptInterface")
    private void initCommonWeb(final String richText){
        commonWeb.loadUrl(richText);
        commonWeb.addJavascriptInterface(AfterSalesActivity.this, "control");
        commonWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                customDialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                //dialog.show();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//接受所有网站的证书，忽略SSL错误

            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(view, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {
//					view.loadUrl("about:blank");// 避免出现默认的错误界面
//                    Toast.makeText(AfterSalesActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
//				view.loadUrl("about:blank");// 避免出现默认的错误界面
//                Toast.makeText(AfterSalesActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
            }

			@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 这个方法在 android 6.0才出现
                int statusCode = errorResponse.getStatusCode();
                if (404 == statusCode || 500 == statusCode) {
//                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                }
            }

        });
        flAddWeb.addView(commonWeb);
    }

	 /**
     * 初始化web
     */
    private void initWeb(final String richText) {

        //初始化webView
        new Handler().postDelayed(new Runnable() {
            @SuppressLint("JavascriptInterface")
            @Override
            public void run() {
                afterSalesWebView.getSettings().setJavaScriptEnabled(true);
                afterSalesWebView.getSettings().setSupportZoom(true);
                afterSalesWebView.getSettings().setBuiltInZoomControls(true);
                afterSalesWebView.getSettings().setDisplayZoomControls(false);
                afterSalesWebView.setVerticalScrollBarEnabled(false);

                afterSalesWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                afterSalesWebView.getSettings().setLoadWithOverviewMode(true);
                afterSalesWebView.getSettings().setUseWideViewPort(true);
                afterSalesWebView.getSettings().setTextZoom(100);

				afterSalesWebView.getSettings().setDomStorageEnabled(true);

                afterSalesWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//默认先不使用缓存
                afterSalesWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
                afterSalesWebView.getSettings().setDefaultTextEncodingName("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    afterSalesWebView.getSettings().setMixedContentMode(afterSalesWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
                }
                afterSalesWebView.loadUrl(richText);
                afterSalesWebView.addJavascriptInterface(AfterSalesActivity.this, "control");
                afterSalesWebView.setWebViewClient(new WebViewClient(){
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        //dialog.show();
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        customDialog.dismiss();
                    }

                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        view.loadUrl(url);
                        return true;
                    }

                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.proceed();//接受所有网站的证书，忽略SSL错误

                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                        super.onReceivedError(view, webResourceRequest, webResourceError);
                        if (webResourceRequest.isForMainFrame()) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
//                            Toast.makeText(AfterSalesActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                        super.onReceivedError(view, errorCode, description, failingUrl);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            return;
                        }
//                        view.loadUrl("about:blank");// 避免出现默认的错误界面
//                        Toast.makeText(AfterSalesActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                        super.onReceivedHttpError(view, request, errorResponse);
                        // 这个方法在 android 6.0才出现
                        int statusCode = errorResponse.getStatusCode();
                        if (404 == statusCode || 500 == statusCode) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
                        }
                    }
                });

            }
        }, 100);

    }

    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (afterSalesWebView != null) {
            //加载null内容
            afterSalesWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            afterSalesWebView.clearHistory();
            //移除WebView
            ((ViewGroup) afterSalesWebView.getParent()).removeView(afterSalesWebView);
            //销毁VebView
            afterSalesWebView.destroy();
            //WebView置为null
            afterSalesWebView = null;
        }
        super.onDestroy();
    }
}
